package com.shuqi.common;

import java.net.URL;
import java.util.regex.Pattern;

import android.content.Context;
import android.text.TextUtils;

import com.shuqi.common.utils.Log4an;
import com.shuqi.model.sharedprefs.WebDomains;

public class WebkitUrlDealer {
    private final String logTag = "WebkitUrlDealer";
    private Pattern pattern;
    private Context context;

    public WebkitUrlDealer(Context context) {
        this.context = context;

        String[] domains;// 书旗的域名数组
        // .*((shuqi\.com)|(yisou\.com)).*
        StringBuilder sb = new StringBuilder(1000);// 把需要匹配的域名添加到正则表达式里
        String str = WebDomains.getInstence().getShuqiWebDomains(context);
        Log4an.i(logTag, "书旗网站动态域名："+str);

        if (str != null && !TextUtils.isEmpty(str.trim())) {
            domains = str.split(",");
        } else {
            domains =
                    new String[] {"11222.cn", "3gpp.net.cn", "4g.net.cn", "53wap.com",
                            "jubaos.com", "3gpp.cn", "ppmix.com", "shuqi.com", "shuqi4.com",
                            "shuqibook.com", "shuqinovel.com", "shuqiread.com", "shuqireader.com",
                            "wappp.cn", "wappp.com", "yisou.com","sm.cn"};
        }
        sb.append(".*(");
        for (int i = 0; i < domains.length; i++) {
            if (TextUtils.isEmpty(domains[i])) {
                continue;
            }
            sb.append("(").append(domains[i].replace(".", "\\.")).append(")|");
        }
        sb.deleteCharAt(sb.length() - 1);// 删除最后一个多余的|
        sb.append(").*");
        pattern = Pattern.compile(sb.toString());
    }

//    public String dealUrl(StringBuilder url) {
//        Log4an.d(logTag, "dealUrl() 之前 url = " + url.toString());
//        // 判断url是否符合要求，如果符合则添加参数，否则忽略
//        // appfunction=an_bmk,1_clo,1
//        // clo,1:H5制作书单页关闭浏览器
//        if (pattern != null && pattern.matcher(url.toString()).matches()) {
//            Log4an.d(logTag, "url matcher ok");
//            int index = url.indexOf("?");
//            if (index >= 0) {// 包含？
//                url.insert(index + 1, "session="
//                        + MyAccountManager.getInstance(context).getSession() + "&"
//                        + "appfunction=an_bmk,1_clo,1_smjs,1&" + ConfigVersion.getVersion() + "&");
//            } else {
//                url.append("?");
//                url.append("session=").append(MyAccountManager.getInstance(context).getSession())
//                        .append("&").append("appfunction=an_bmk,1_clo,1_smjs,1").append("&")
//                        .append(ConfigVersion.getVersion());
//            }
//        }
//        Log4an.d("dealurl", "dealUrl() 之后    url = " + url.toString());
//        return url.toString();
//    }
    
    public String dealUrl(StringBuilder url) {
        return dealUrl(url.toString());
    }
    public String dealUrl(String url) {
        if (url!=null && url.length()>0 && pattern != null && pattern.matcher(url.toString()).matches()) {
            return addAppPrams(url.toString());
        }
        Log4an.e(logTag, "addAppPrams 该地址不在书旗域名列表: "+url);
        return url.toString();
    }
    
    /**
     * 添加客户端一系列参数和appfunction参数/支持最新版#!锚点格式的参数
     * @param targetUrl 处理前的url地址
     * @return
     */
    public String addAppPrams(String targetUrl){
        if(targetUrl==null || "".equals(targetUrl) || !targetUrl.startsWith("http")){
            Log4an.e("error url : "+targetUrl);
            return targetUrl;
        }
        Log4an.i(logTag, "addAppPrams 之前："+targetUrl);

        try {
            URL url = new URL(targetUrl);
            StringBuilder builder = new StringBuilder();
            
            //添加协议
            String mProtocol = url.getProtocol();
            builder.append(mProtocol);
            
            //添加主机名
            String mHost = url.getHost();
            builder.append("://").append(mHost);
            
            //添加端口
            int mPort = url.getPort();
            String prot = -1==mPort?"":(":"+mPort);
            builder.append(prot);
            
            //添加路径
            String mPath = null==url.getPath()?"":url.getPath();
            builder.append(mPath);
            
            //添加客户端参数
            builder.append("?").append("appfunction=an_bmk,1_clo,1_smjs,1&");
            builder.append(ConfigVersion.getVersion());
            
            //添加查询参数
            String mQuery = url.getQuery();
            if(!TextUtils.isEmpty(mQuery)){
                builder.append("&");
                builder.append(mQuery);
            }
            
            //添加锚点
            String mRef = url.getRef();
            if(mRef==null){
                mRef = "";
            }else{
                mRef = "#"+mRef;
            }
            builder.append(mRef);
            
            targetUrl = builder.toString();
            
            //清理内存
            builder.setLength(0);
            builder = null;
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log4an.e(logTag, "addAppPrams 之后："+targetUrl);
        return targetUrl;
    }
}
